﻿using System;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;
using scheduler.Model;

namespace scheduler
{
    public class EmailReminder : IReminder
    {
        public TodoInfo TodoInfo { get; set; }

        private EmailReminderInfo _info;

        public ReminderInfo Info
        {
            get { return _info; }
            set { _info = value as EmailReminderInfo; }
        }

        public void Execute()
        {
            if(string.IsNullOrEmpty(_info.To))
            {
                App.Logger.Log("bad reminder email address for " + 
                    TodoInfo.Title + "@" + TodoInfo.File);
                return;
            }
            App.Logger.Log("Sending email.. [Todo:" + TodoInfo.Title + "] to " + _info.To);

            var client = new SmtpClient("smtp.163.com");

            client.UseDefaultCredentials = false;
            var cred = new NetworkCredential("todoexe", "password");
            client.Credentials = cred;

            var from = new MailAddress("todoexe@163.com",
                    "Todo Reminder", Encoding.UTF8);
            var to = new MailAddress(_info.To);

            var message = new MailMessage(from, to);

            var subject = "Todo: " + TodoInfo.Title;
            if (!string.IsNullOrEmpty(TodoInfo.Due))
            {
                subject += "@" + TodoInfo.Due;
            }
            message.Subject = subject;
            message.SubjectEncoding = Encoding.UTF8;

            var sb = new StringBuilder();
            for (var n = 0; n < TodoInfo.PathTitles.Length; n++)
            {
                sb.AppendLine(new string(' ', n * 2) + TodoInfo.PathTitles[n]);
                if(n > 0)
                {
                    sb.Append("      ");
                }
            }
            message.Body = "Todo: " + sb + 
                           "Description: " + TodoInfo.Description + Environment.NewLine +
                           "Due: " + TodoInfo.Due + Environment.NewLine +
                           "File: " + TodoInfo.File;
            message.BodyEncoding = Encoding.UTF8;

            client.SendAsync(message, null);
//            message.Dispose();
        }
    }
}